import { useAsyncEffect } from '@gnlab/utils/env-react'
import { Switch, App } from 'antd'
import { EditModal } from '@/desktop/components'
import services from '@/services'
import './index.module.less'

export { ReactComponent as Icon } from './icon.svg'

export function AutoApplyContact({ open, onClose }: { open: boolean; onClose: () => void }) {
  return <EditModal
    styleName="modal"
    title="自动通过好友申请"
    width="500px"
    open={open}
    onCancel={onClose}
  >
    {open ? <Content /> : null}
  </EditModal>
}

function Content() {
  const { message } = App.useApp()
  const [enable, setEnable] = useState<boolean | null>(null)

  useAsyncEffect(async () => {
    const res = await services.features.autoApplyContact.get()
    if (res.success) {
      setEnable(res.data)
    } else {
      void message.warning(`获取设置失败：${res.error}`)
      setEnable(false)
    }
  }, [])

  const save = useCallback(
    async (enable: boolean) => {
      setEnable(enable)
      const res = await services.features.autoApplyContact.save(enable)
      if (res.success) void message.success('修改成功')
      else void message.warning(`修改失败：${res.error}`)
    },
    [message],
  )

  return <main>
    <header>开启后，当企业微信收到新好友申请时（仅限个微好友），将自动通过。</header>
    <div>
      自动通过：
      <Switch
        disabled={enable === null}
        checkedChildren="开启"
        unCheckedChildren="关闭"
        checked={enable ?? false}
        onChange={save}
      />
    </div>
  </main>
}
